package com.alan.netty.nio.buffers;

import java.nio.Buffer;
import java.nio.ByteBuffer;

/**
 * @author weiBin
 * @date 2018/11/6
 */
public class BufferAccess {
    public static void main(String[] args) {
        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(10);
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }
        printBuffer(buffer);
        //切换读模式
        buffer.flip();
        for (int i = 0; i < 5; i++) {
            System.out.println(buffer.get());
        }
        printBuffer(buffer);
        //position 移动至2  limit 设置为5
        buffer.position(2).limit(5);
        printBuffer(buffer);
        //标记
        buffer.mark();
        System.out.println(buffer.get());
        //回滚到标记
        buffer.reset();
        System.out.println(buffer.get());
        printBuffer(buffer);
        //切换到写模式 未读取的数据移动到最前面 position 设置其长度
        buffer.compact();
        printBuffer(buffer);
        //切换到读模式
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.println(buffer.get());
        }
        buffer.position(2).limit(8);
        //清空 position 归0
        buffer.clear();
        printBuffer(buffer);
    }

    private static void printBuffer(Buffer buffer) {
        System.out.println("[limit=" + buffer.limit()
                + ", position = " + buffer.position()
                + ", capacity = " + buffer.capacity()
                + ",remaining =" + buffer.remaining()
                + ", array = " + buffer.toString() + "]");
    }
}
